package middleware

import (
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"

    "github.com/samaa/photosalesplus/backend/internal/handlers"
    "github.com/samaa/photosalesplus/backend/internal/services"
)

type MerchantAuthMiddleware struct{ svc services.MerchantAuthService }

func NewMerchantAuthMiddleware(s services.MerchantAuthService) *MerchantAuthMiddleware { return &MerchantAuthMiddleware{svc: s} }

// Handle validates merchant token and injects merchant_id
func (m *MerchantAuthMiddleware) Handle(c *gin.Context) {
    // read header
    auth := c.GetHeader("Authorization")
    token := ""
    if auth != "" {
        parts := strings.SplitN(auth, " ", 2)
        if len(parts) == 2 && strings.EqualFold(parts[0], "Bearer") {
            token = strings.TrimSpace(parts[1])
        }
    }
    if token == "" {
        token = c.Query("token")
    }
    id, ok := m.svc.Validate(c.Request.Context(), token)
    if !ok {
        c.AbortWithStatusJSON(http.StatusUnauthorized, handlers.APIResponse{Error: "商户未授权"})
        return
    }
    c.Set("merchant_id", id)
    c.Set("merchant_token", token)
    c.Next()
}

